from datetime import datetime
from sql import sqlseverDB
from config import *
from tool import change_task_status
import concurrent.futures as thddd
import requests
import sys,time

tms = sqlseverDB('{SQL Server}', SQL_SERVER, 'SuMaiTongPol', SQL_USER, SQL_PWD)
session=requests.session()

session.headers={
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': 'Bearer sk-3c8ae8738d91498bbdcffc76bd0345b1'
}
def req_ppd(typ,tit,j):
    url = "https://api.deepseek.com/chat/completions"
    question=f'''将以下SKU翻译成印尼语，要求：
            1. 仅返回翻译结果，不要额外解释
            2. SKU必须完全去除中文，使用缩写（如4pc、Std、Hijau）
            3. SKU总长度（包括空格和符号）严格≤20字符
            4. 如果超长，优先截断或使用更短单词,并缩写至字符串长度等于20
            {tit}'''

    payload = {
        "messages": [
            {
                "content": question,
                "role": "user"
            }
        ],
        "model": "deepseek-chat",
        "frequency_penalty": 0,
        "max_tokens": 2048,
        "presence_penalty": 0,
        "response_format": {
            "type": "text"
        },
        "stop": None,
        "stream": False,
        "stream_options": None,
        "temperature": 1,
        "top_p": 1,
        "tools": None,
        "tool_choice": "none",
        "logprobs": False,
        "top_logprobs": None
    }
    
    try:
        res = session.post( url,json=payload,timeout=60)
        if res.status_code==200:
            js_data=res.json()
            #print(js_data)
            ppd=js_data['choices'][0]['message']['content']
            return [j,typ,tit,ppd]
        else:
            print(f'第{j}个sku:《{tit}》,状态码出错 => {e}')

    except Exception as e:
        print(f'第{j}个sku:《{tit}》,匹配度请求出错 => {e}')


def main():


    while True:
        st_time=time.time()
        rs=tms.ExecQuery("select distinct sku1 from S1688ProSKU where len(ynsku1)>20")
        rs2=tms.ExecQuery("select distinct sku2 from S1688ProSKU where len(ynsku2)>20")
        #rs=[(1176,'4069800374601','tiara Barokowy Vintage Metal korona króla królewsk')]
        task_count=len(rs)+len(rs2)
        if task_count==0:
            print(f'sku全部更新完毕,退出采集')
            break
        print(f'本轮需采集:{task_count}标题')
        with thddd.ThreadPoolExecutor(max_workers=10) as t:

            tasks=[]
            j=1
            for r in rs:
                sku1=r[0]
                tasks.append(t.submit(req_ppd,'sku1',sku1,j))
                j+=1
            
            for r in rs2:
                sku2=r[0]
                tasks.append(t.submit(req_ppd,'sku2',sku2,j))
                j+=1

            
            for t0 in thddd.as_completed(tasks):
                res=t0.result()
                if res is not None:
                    res_j,res_ryp,res_cnsku,res_ynsku=res
                   
                    aff2=tms.ExecNoQuery(f"update S1688ProSKU set yn{res_ryp}='{res_ynsku}' where {res_ryp}=?",(res_cnsku,))
                    print(f'第 {res_j} 个{res_ryp}:《{res_cnsku}》,成功翻译成:《{res_ynsku}》,长度:{len(res_ynsku)},更新S1688ProSKU行数:{aff2}')
                
                task_count-=1
                print(f'剩余采集侵权任务:{task_count}/{len(rs)}')
        ed_time=time.time()
        hs=(ed_time-st_time)/3600
        print(f'本轮更新sku任务完毕,耗时: {hs:.2f} 小时')

        time.sleep(10)


if __name__=='__main__':

    main()



